﻿using System;
using System.Web;
using Castle.MonoRail.Framework;

namespace Hadlow.Jobvertizer.Models
{
    public class SecurityHelper : ISecurityHelper
    {
        IRailsEngineContext context;

        // I don't like having the controller set the context here, but I can't see any other
        // way to do it currently
        public IRailsEngineContext Context
        {
            set { this.context = value; }
            get { return this.context; }
        }

        private void CheckContext()
        {
            if (this.context == null)
                throw new ApplicationException("Context property is not set.");
        }

        public bool UserIsLoggedIn
        {
            get 
            {
                CheckContext();
                return !context.CurrentUser.IsInRole(Role.Guest.Name);
            }
        }

        public User CurrentUser
        {
            get
            {
                CheckContext();
                User user = context.CurrentUser as User;
                if (user == null) throw new ApplicationException("context.CurrentUser is not a " + typeof(User).ToString());
                return user;
            }
        }
    }
}
